package com.biz.user.service.impl;

import com.alibaba.fastjson.*;
import com.biz.user.dao.es.*;
import com.biz.user.entity.po.*;
import com.biz.user.service.*;
import lombok.extern.slf4j.*;
import org.elasticsearch.index.query.*;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.document.*;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.util.*;

/**
 * @Description
 * @Author liuxi
 * @Date 2024/6/10
 **/
@Service
@Slf4j
public class UserEsServiceImpl implements UserEsService {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private UserEsRepository userEsRepository;

    @Override
    public void createIndex() {
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(UserEsPo.class);
        indexOperations.create();
        Document mapping = indexOperations.createMapping(UserEsPo.class);
        indexOperations.putMapping(mapping);
    }

    @Override
    public void addDocs() {
        List<UserEsPo> list = new ArrayList<>();
        list.add(new UserEsPo(1L, "测试", "测试123456789", "123", new Date()));
        list.add(new UserEsPo(2L, "测试2", "测试123456789", "456", new Date()));
        userEsRepository.saveAll(list);
    }

    @Override
    public void find() {
        UserEsPo userEsPo = userEsRepository.findById(1L).orElse(new UserEsPo());
        List<UserEsPo> byName = userEsRepository.findByName("测试");
    }

    @Override
    public void search() {
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("name", "测试"))
                .build();
        SearchHits<UserEsPo> search = elasticsearchRestTemplate.search(nativeSearchQuery, UserEsPo.class);
        List<SearchHit<UserEsPo>> searchHits = search.getSearchHits();
        log.info("searchHits{}", JSON.toJSONString(searchHits));
    }
}
